<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="616px"
      :title="tenantCode ? '租户菜单配置【编辑】' : '新增租户菜单配置'"
      wrapClassName="tenant-modal-container"
      @cancel="closeModal()"
    >
      <div class="tenant-modal-body">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <!-- 选择租户 -->
          <a-form-model-item ref="tanant" label="选择租户" prop="tanant">
            <a-tree-select
              :disabled="tenantCode ? true : false"
              placeholder="请选择租户名称"
              :replaceFields="{
                children: 'child',
                title: 'tenantName',
                key: 'id',
                value: 'tenantCode',
              }"
              v-model="form.tanant"
              :tree-data="tanantSource"
              @change="tanantChange($event)"
            >
            </a-tree-select>
          </a-form-model-item>
          <!-- 权限菜单 -->
          <a-form-model-item
            ref="permisionMenu"
            label="权限菜单"
            prop="permisionMenu"
          >
            <div
              class="permision-menu-container"
              :class="noChoosePermissFlag && 'error'"
              v-loading="menuLoading"
            >
              <a-empty :image="simpleImage" v-if="treeData.length == 0" />
              <a-tree
                ref="menuTree"
                v-model="checkedKeys"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :tree-data="treeData"
                :replaceFields="{
                  children: 'childs',
                  title: 'menuName',
                  key: 'id',
                }"
                @expand="onExpand"
                @check="onCheck"
              />
            </div>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="form-footer flex">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button
          type="primary"
          :disabled="buttonFlag"
          :loading="loading"
          @click="submitForm()"
        >
          提交
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getLoginData } from "@/tools";
import { getTenantList } from "@/api/user-center/organizationManage.js";
import { getTenantPermissionList } from "@/api/user-center/tenantManage.js";
import {
  saveOrUpdate,
  getTenantConfigDetail,
} from "@/api/user-center/roleManage.js";
import { addAttributeByKey, flatTreeData } from "@/utils";
import { Empty } from "ant-design-vue";
export default {
  name: "tenantConfigModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    tenantCode: {
      type: String,
      default: "",
    },
    roleId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      form: {
        tanant: undefined,
        permisionMenu: undefined,
      },
      tanantSource: [],
      tanantLoading: false,
      rules: {
        tanant: [{ required: true, message: "请选择租户", trigger: "change" }],
        permisionMenu: [
          { required: true, validator: this.checkAge, trigger: "change" },
        ],
      },
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      treeData: [],
      noChoosePermissFlag: false,
      menuLoading: false,
      halfKeysData: [],
      buttonFlag: true,
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.$emit("update:visible", val);
          this.form.tanant = this.tenantCode || undefined;
          this.getTenantList();
          this.getTenantPermissionList();
        }
      },
      immediate: true,
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {},
  methods: {
    //查询详情
    getDetail() {
      if (!this.form.tanant) {
        return;
      }
      return new Promise((resolve, reject) => {
        let { tanant } = this.form;
        getTenantConfigDetail({ roleId: this.roleId, tenantCode: tanant })
          .then((res) => {
            let { data } = res;
            this.checkedKeys = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.checkedKeys = [];
            reject();
          });
      });
    },
    //查询权限菜单
    getTenantPermissionList() {
      if (!this.form.tanant) {
        return;
      }
      this.menuLoading = true;
      return new Promise((resolve, reject) => {
        getTenantPermissionList({
          menuName: "",
          menuTypeValue: "",
          tenantCode: this.form.tanant,
        })
          .then((res) => {
            let { data } = res;
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              data?.result || [],
              "childs"
            );
            let ids = flatTreeData(this.treeData, "childs").map((v) => v.id);
            this.expandedKeys = ids || [];

            this.getDetail();

            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.menuLoading = false;
          });
      });
    },

    tanantChange() {
      this.checkedKeys = [];
      this.getTenantPermissionList();
    },

    //【查询条件】查询项目名称
    getTenantList() {
      this.tanantLoading = true;
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getTenantList({ userId })
          .then((res) => {
            let { data } = res;
            let tree = data?.result || [];
            this.tanantSource = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              tree,
              "child"
            );
            resolve();
          })
          .catch((_) => {
            this.tanantSource = [];
            reject();
          })
          .finally((_) => {
            this.form.tanant = this.tenantCode || undefined;
            this.tanantLoading = false;
          });
      });
    },

    //关闭弹窗
    closeModal() {
      this.$refs.ruleForm.resetFields();
      this.$emit("update:visible", false);
      this.loading = false;
      this.form = {
        tanant: undefined,
        permisionMenu: undefined,
      };
      this.tanantSource = [];
      this.tanantLoading = false;
      this.expandedKeys = [];
      this.autoExpandParent = true;
      this.checkedKeys = [];
      this.halfKeysData = [];
      this.treeData = [];
      this.noChoosePermissFlag = false;
      this.menuLoading = false;
      this.buttonFlag = true;
    },

    //提交
    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let { id = "" } = this.$route.query;
          this.loading = true;
          let menuIds = Array.from(
            new Set([...this.checkedKeys, ...this.halfKeysData])
          );
          saveOrUpdate({
            roleId: id,
            tenantCode: this.tenantCode || this.form.tanant,
            permissionsIds: menuIds.toString(),
          })
            .then((res) => {
              let { data } = res;
              if (data?.result) {
                this.$message.success("操作成功");
              } else {
                this.$message.error("操作失败，请稍后重试！");
              }
              this.$parent.getTenantMenuByRoleId();
              this.closeModal();
            })
            .catch((_) => {
              this.$message.error("操作失败，请稍后重试！");
            })
            .finally((_) => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },

    //自定义权限菜单校验
    checkAge(rule, value, callback) {
      let { checkedKeys } = this;
      if (checkedKeys.length == 0) {
        this.noChoosePermissFlag = true;
        return callback(new Error("请选择权限菜单"));
      } else {
        this.noChoosePermissFlag = false;
        callback();
      }
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys, ev) {
      let { halfCheckedKeys } = ev;
      this.halfKeysData = halfCheckedKeys;
      this.noChoosePermissFlag = false;
      this.checkedKeys = checkedKeys;
      this.$refs.permisionMenu.onFieldChange();
      this.buttonFlag = false;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.tenant-modal-container {
  /deep/.ant-empty {
    margin: 0;
  }
  .ant-modal-body {
    padding: 20px 60px;
    .tenant-modal-body {
      margin-bottom: 40px;
      .ant-form-item {
        .flex();
        .ant-form-item-label {
          flex-shrink: 0;
          width: 80px;
        }
        .ant-form-item-control-wrapper {
          flex: 1;
        }
        .permision-menu-container {
          width: 414px;
          height: 278px;
          background: #ffffff;
          border: 1px solid #d4d7d8;
          border-radius: 4px;
          .custom-scrollbar();
          &.error {
            border-color: red;
          }
          .ant-tree {
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                width: calc(100% - 60px);
              }
            }
          }
        }
      }
    }
    .form-footer {
      justify-content: center;
    }
  }
}
</style>
